﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DayPilot.Web.Mvc;
using DayPilot.Web.Mvc.Enums;
using DayPilot.Web.Mvc.Events.Calendar;
using ESupervision.Models;
using Microsoft.AspNet.Identity;
using System.Net;
using System.Threading.Tasks;

namespace ESupervision.Controllers
{
    [Authorize]
    public class MeetingController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        //
        // GET: /Meeting/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Backend()
        {
            return new Dpc().CallBack(this);
        }
        public ActionResult StudentMeeting()
        {
            return new Dpc2().CallBack(this);
        }
        public ActionResult ViewMessage(string message)
        {
            return View("Index");
        }
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            MeetingEvent ev = await db.MeetingEvents.FindAsync(id);
            if (ev == null)
            {
                return HttpNotFound();
            }
            return View(ev);
        }

        class Dpc : DayPilotCalendar
        {
            private ApplicationDbContext db = new ApplicationDbContext();
            private string userId = System.Web.HttpContext.Current.User.Identity.GetUserId();
            protected override void OnInit(InitArgs e)
            {
                Update(CallBackUpdateType.Full);
            }

            protected override void OnEventResize(EventResizeArgs e)
            {
                int id = Convert.ToInt32(e.Id);
                var toBeResized = (from ev in db.MeetingEvents where ev.MeetingEventID == id select ev).First();
                if (toBeResized != null && toBeResized.OrganizerUserID == userId)
                {
                    toBeResized.StartTime = e.NewStart;
                    toBeResized.EndTime = e.NewEnd;
                    toBeResized.AlertTime = e.NewStart.AddDays(-3);
                    db.SaveChanges();
                    Update();
                }
                else
                {
                    Controller.TempData["msg"] = "<script>alert('You is not Meeting Organizer. So, You can not change meeting information');</script>";
                    Redirect("~/Meeting/Index");
                }
            }

            protected override void OnEventMove(EventMoveArgs e)
            {
                int id = Convert.ToInt32(e.Id);
                var toBeResized = (from ev in db.MeetingEvents where ev.MeetingEventID == id select ev).First();
                if (toBeResized != null && toBeResized.OrganizerUserID == userId)
                {
                    toBeResized.StartTime = e.NewStart;
                    toBeResized.EndTime = e.NewEnd;
                    toBeResized.AlertTime = e.NewStart.AddDays(-3);
                    db.SaveChanges();
                    Update();
                }
                else
                {
                    Controller.TempData["msg"] = "<script>alert('You is not Meeting Organizer. So, You can not change meeting information');</script>";
                    Redirect("~/Meeting/Index");
                }
            }

            protected override void OnTimeRangeSelected(TimeRangeSelectedArgs e)
            {
                string name = (string)e.Data["name"];
                string content = (string)e.Data["content"];
                if (name.Trim().Length <= 0 || content.Trim().Length <= 0)
                {
                    Controller.TempData["msg"] = "<script>alert('Enter meeting name, enter meeting content');</script>";
                    Redirect("~/Meeting/Index");
                }
                else
                {
                    var toBeCreated = new MeetingEvent
                    {
                        Status = MeetingEventStatus.New,
                        Subject = (string)e.Data["name"],
                        Body = (string)e.Data["content"],
                        OrganizerUserID = userId,
                        StartTime = e.Start,
                        EndTime = e.End,
                        AlertTime = e.Start.AddDays(-3),
                    };
                    db.MeetingEvents.Add(toBeCreated);
                    db.SaveChanges();
                    Update();
                }
            }

            protected override void OnFinish()
            {
                if (UpdateType == CallBackUpdateType.None)
                {
                    return;
                }
                var MeetingOrganizer = db.MeetingEvents.Where(e => e.OrganizerUserID == userId);
                var RequestedMeeting = from m in db.MeetingEvents
                                       join p in db.MeetingEventParticipants on m.MeetingEventID equals p.MeetingEventID
                                       where p.RequestedUserID == userId
                                       select m;
                Events = MeetingOrganizer.Union(RequestedMeeting);

                DataIdField = "MeetingEventID";
                DataTextField = "Subject";
                DataStartField = "StartTime";
                DataEndField = "EndTime";
            }
            protected override void OnEventClick(EventClickArgs e)
            {
                int id = Convert.ToInt32(e.Id);
                if (id <= 0)
                {
                    return;
                }
                MeetingEvent ev = db.MeetingEvents.Find(id);
                if (ev == null)
                {
                    return;
                }
                else
                {
                    Redirect("~/Meeting/Details/" + id);
                }
            }
        }

        class Dpc2 : DayPilotCalendar
        {
            private ApplicationDbContext db = new ApplicationDbContext();
            private string userId = System.Web.HttpContext.Current.User.Identity.GetUserId();
            protected override void OnInit(InitArgs e)
            {
                Update(CallBackUpdateType.Full);
            }

            protected override void OnFinish()
            {
                if (UpdateType == CallBackUpdateType.None)
                {
                    return;
                }
                Events = from m in db.MeetingEvents
                                       join p in db.MeetingEventParticipants on m.MeetingEventID equals p.MeetingEventID
                                       where p.RequestedUserID == userId
                                       select m;
                DataIdField = "MeetingEventID";
                DataTextField = "Subject";
                DataStartField = "StartTime";
                DataEndField = "EndTime";
            }
            protected override void OnEventClick(EventClickArgs e)
            {
                int id = Convert.ToInt32(e.Id);
                if (id <= 0)
                {
                    return;
                }
                MeetingEvent ev = db.MeetingEvents.Find(id);
                if (ev == null)
                {
                    return;
                }
                else
                {
                    Redirect("~/Meeting/Details/" + id);
                }
            }
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}